package org.xiaoyu.rpc.registry.nacos;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.pojo.Instance;
import lombok.extern.slf4j.Slf4j;
import org.xiaoyu.rpc.common.url.URL;

import java.util.List;

/**
 * Created By Have
 * 2021/7/5 20:09
 */
@Slf4j
public class NacosNamingServiceWrapper {
    private  NamingService namingService;

    public NacosNamingServiceWrapper(NamingService namingService) {
        this.namingService = namingService;
    }

    public void registerService(URL url) throws NacosException {
        Instance instance = new Instance();
        instance.addMetadata("serviceUniqueName", url.getServiceUniqueName());
        instance.addMetadata("host", url.getHost());
        instance.addMetadata("port", String.valueOf(url.getPort()));
        instance.addMetadata("version", url.getVersion());
        instance.addMetadata("serviceName", url.getServiceName());
        instance.addMetadata("weight", String.valueOf(url.getWeight()));
        instance.addMetadata("path", url.getAllPath());

        namingService.registerInstance(url.getServiceName(), url.getGroup(), instance);
    }

    public List<Instance> getAllInstance(String serviceName) throws NacosException {
        return namingService.getAllInstances(serviceName, "public");
    }

    public void subscribe(String serviceName, EventListener listener) throws NacosException{
        namingService.subscribe(serviceName, listener);
    }

    public void subscribe(String serviceName, String group, EventListener listener) throws NacosException{
        namingService.subscribe(serviceName, group, listener);
    }

    public void shutdown() throws NacosException {
        namingService.shutDown();
    }
}
